using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Theodorus.Properties;

namespace Theodorus
{
    class TextResultsRenderer : IResultsRenderer
    {
        private readonly List<string> _text = new List<string>();

        public void Reset()
        {
            _text.Clear();
        }

        public void AddError(string query, string errorMessage)
        {
            _text.Add("Error:");
            _text.Add(query);
            _text.Add(errorMessage);
            _text.Add("");
        }

        public void AddResponse(string query, string result, TimeSpan timings)
        {
            _text.Add(String.Format("Result: Elapsed {0} ms", timings.TotalMilliseconds));
            _text.Add(query);
            _text.Add(result);
            _text.Add("");
        }

        public void AddTable(string query, DataTable table, TimeSpan timings)
        {
        	_text.Add(String.Format("Result: Elapsed {0} ms", timings.TotalMilliseconds));
            _text.Add(query);
           
            _text.Add(table.Columns.Cast<DataColumn>().Select(item => item.ColumnName)
                .Aggregate((a, b) => a + "," + b));

        	var rowCount = 0;
            foreach (DataRow row in table.Rows)
            {
				_text.Add(row.ItemArray.Select(item => item.ToString())
                    .Aggregate((a, b) => a + "," + b));

            	rowCount++;

				if (rowCount == Settings.Default.ResultsLimit) break;
            }
            _text.Add("");
        }

        public string GetResults()
        {
            return _text.Aggregate((a, b) => a + Environment.NewLine + b);
        }

        public bool HasResults()
        {
            return _text.Count > 0;
        }
    }
}